package orders

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"insighttracking/common/utils"
	"insighttracking/query/dao"
	"insighttracking/query/service"
	"net/http"

	"insighttracking/apps/customer/internal/svc"
	"insighttracking/apps/customer/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetOrdersDetailApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetOrdersDetailApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetOrdersDetailApiLogic {
	hostname, _ := os.Hostname()
	return &GetOrdersDetailApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetOrdersDetailApiLogic) GetOrdersDetailApi(req *types.IdReq) (resp *types.OrdersResp, err error) {
	// todo: add your logic here and delete this line
	ordersEntity, err := dao.OrdersEntity.WithContext(l.ctx).Where(dao.OrdersEntity.ID.Eq(req.Id)).First()
	if err != nil {
		logx.Errorf("传递的订单号错误:%d", req.Id)
		return nil, errors.New("查询失败")
	}
	// 查询订单详情
	orderSpu, _ := service.OrdersSpuService.GetListByOrdersIDApi(l.ctx, req.Id)
	//detailEntities, _ := dao.OrdersDetailEntity.WithContext(l.ctx).Where(dao.OrdersDetailEntity.OrdersID.Eq(req.Id)).Find()
	var detailList = make([]*types.OrdersSpuResp, 0)
	for _, item := range orderSpu {
		var packageCount, receivedPackageCount, status int64
		if item.DeliveryStatus == 20 {
			status = 10
		}
		if item.ReceiveStatus == 20 {
			status = 20
		}
		packageCount, _ = service.ProductionSortingService.GetPackedCount(l.ctx, item.ID)
		receivedPackageCount, _ = service.ProductionSortingService.GetReceivedCount(l.ctx, item.ID)
		if receivedPackageCount < packageCount && receivedPackageCount > 0 {
			status = 15
		}
		detailList = append(detailList, &types.OrdersSpuResp{
			ID:                   item.ID,
			SpuID:                item.SpuID,
			CatogoryName:         item.CatogoryName,
			PackageCount:         packageCount,
			ProductionImageURL:   item.ProductImageURL,
			ReceivedPackageCount: receivedPackageCount,
			RequireCount:         item.RequireCount.InexactFloat64(),
			SpuName:              item.SpuName,
			Status:               status,
			UnitName:             item.UnitName,
			CreatedAt:            utils.TimestampToString(item.CreatedAt),
		})
	}
	return &types.OrdersResp{
		ID:                 ordersEntity.ID,                                                                                   // 主键id
		OrderNo:            ordersEntity.OrderNo,                                                                              // 订单流水号
		EnterpriseID:       ordersEntity.EnterpriseID,                                                                         // 关联到enterprise表主键id
		CustomerID:         ordersEntity.CustomerID,                                                                           // 客户id,关联到enterprise_customer表主键id
		SendGoodsDate:      k.If(ordersEntity.SendGoodsDate.IsZero(), 0, utils.TimestampToString(ordersEntity.SendGoodsDate)), // 发货日期
		SendGoodsMethod:    ordersEntity.SendGoodsMethod,                                                                      // 发货方式,0表示司机配送
		SettlementMethod:   ordersEntity.SettlementMethod,                                                                     // 结算方式，0表示账期
		PurchaserID:        ordersEntity.PurchaserID,                                                                          // 采购员,关联到
		Remark:             ordersEntity.Remark,                                                                               // 订单备注
		TotalAmount:        ordersEntity.TotalAmount.StringFixed(2),                                                           // 订单金额
		TotalCount:         ordersEntity.TotalCount.StringFixed(2),                                                            // 订单商品数量
		Status:             ordersEntity.Status,                                                                               // 订单状态,0表示已下单(待采购),1表示采购中,2表示已采购,3待入库，4已入库，5已发货,6已收货
		ReceiveGoodsName:   ordersEntity.ReceiveGoodsName,                                                                     // 收货员姓名
		ReceiveGoodsMobile: ordersEntity.ReceiveGoodsMobile,                                                                   // 收货人手机号码
		ReceiveAddress:     ordersEntity.ReceiveAddress,                                                                       // 收货人地址
		IsPurchasingPlan:   ordersEntity.IsPurchasingPlan,                                                                     // 是否发布采购计划,0表示不发布,1表示发布
		CreatedAt:          utils.TimestampToString(ordersEntity.CreatedAt),                                                   // 创建时间
		UpdatedAt:          utils.TimestampToString(ordersEntity.UpdatedAt),                                                   // 更新时间
		DetailList:         detailList,                                                                                        // 商品详情
	}, nil
}
